

package org.koyabr.webx.demo.danmaku.biz.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import com.alibaba.citrus.util.io.StreamUtil;

import org.koyabr.webx.demo.danmaku.biz.DuplicatedPostException;
import org.koyabr.webx.demo.danmaku.biz.PostManager;
import org.koyabr.webx.demo.danmaku.biz.PostManagerException;
import org.koyabr.webx.demo.danmaku.dal.dao.PostDao;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.Danmaku;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.Post;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.dao.DataIntegrityViolationException;

public class PostManagerImpl implements PostManager, InitializingBean {
    private final static String UPLOAD_DIR = "/petstore/upload";

    @Autowired
    private PostDao postDao;

    @Autowired
    private ResourceLoader resourceLoader;

    private File uploadDir;

    public void afterPropertiesSet() {
        try {
            uploadDir = resourceLoader.getResource(UPLOAD_DIR).getFile();

            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            if (!uploadDir.isDirectory()) {
                throw new IOException("Could not create directory " + uploadDir.getAbsolutePath());
            }
        } catch (Exception e) {
            throw new PostManagerException("Could not get upload directory from ResourceLoader: " + UPLOAD_DIR);
        }
    }


    public List<Danmaku> getAllDanmakusByPost(String postId) {
        return postDao.getDanmakusByPostId(postId);
    }

    public void addDanmaku(Danmaku danmaku){
    	postDao.insertDanmaku(danmaku);
    	
    }

    
    public void addPost(Post post, FileItem picture) throws PostManagerException {
        String imageFileName;

        try {
            imageFileName = getPictureName(picture);
        } catch (IOException e) {
            throw new PostManagerException(e);
        }

        post.setPictureFile(imageFileName);

        try {
            postDao.insertPost(post);
        } catch (DataIntegrityViolationException e) {
            throw new DuplicatedPostException(post.getTitle());
        }
    }

    /**
     * 根据用户上传的图像文件，转化成服务器上的永久文件，并返回文件名
     * @param picture 用户上传的图像文件
     * @throws IOException
     */
    private String getPictureName(FileItem picture) throws IOException {
        String imageFileName = null;

        if (picture != null) {
        	//去除路径
            String fileName = picture.getName().replace('\\', '/');
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

            //获得扩展名
            String ext = "";
            int index = fileName.lastIndexOf(".");
            if (index > 0) {
                ext = fileName.substring(index);
            }

            //创建临时文件
            File imageFile = File.createTempFile("image_", ext, uploadDir);
            imageFileName = imageFile.getName();

            //写入图像文件数据
            InputStream is = picture.getInputStream();
            OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile));
            StreamUtil.io(is, os, true, true);
        }

        return imageFileName;
    }
    
    public Post getPostById(String postId){
    	return postDao.getPostById(postId);
    }
    
    public Post getPostByTitle(String title){
    	return postDao.getPostByTitle(title);
    }
    
    public List<Post> getAllPostsByCategory(String category, String sortSeed, String sortOrder){
    	return postDao.getPostsByCategory(category, sortSeed, sortOrder);
    }
    
    public List<Post> getAllPostsByAuthor(String username, String sortSeed, String sortOrder){
    	return postDao.getPostsByAuthor(username, sortSeed, sortOrder);
    }
    

    public List<Post> getAllPostsByAutAndCat(String username, String category, String sortSeed, String sortOrder){
    	return postDao.getPostsByAutAndCat(username, category, sortSeed, sortOrder);
    }
    

    public List<Post> getAllPosts(String sortSeed, String sortOrder){
    	return postDao.getAllPosts(sortSeed, sortOrder);
    }
    
}
